import {stringify} from "qs";
import {recordRoute} from "/@/config";
import {hasPermission} from "/@/utils/permission";
import {isExternal} from "/@/utils/validate";
import Page404 from "/@/views/error/404.vue";
import Layout from "/@vab/layouts/index.vue";

import AppUtil from "/@/utils/app";



export const convertRouter = (asyncRoutes: MenuRecord[],parent?:MenuRecord) => {

    let componentMap = AppUtil.getComponentMap(); //本地组件列表
    for (let route of asyncRoutes) {

        route.children = route.children ?  route.children.sort((a, b) => a.sort - b.sort): []
        if (!route.meta) {
            route.meta = {}
        }

        if (parent) {
            route.level = parent.level + 1
        } else {
            route.level = 1
            route.meta.noColumn = route.children.length < 2
        }
        route.path = route.url === '' ? '' : parent ? parent.path+ route.url : route.url
        route.name = route.routeName ||  route.path
        delete route.url
        route.meta.title = route.menuName || '';
        route.meta.hidden = route.visible == 1
        route.meta.icon = route.icon ?? ''
        if (route.visible == 1) {
            console.log(route.visible);
        }
        if (route.pid == '0') {
            if (route.component) {
                route.children = [{
                    url: "",
                    path: "",
                    pid: "",
                    level: 0,
                    title: "",
                    visible: 0,
                    sort: 0,
                    name: "",
                    routeName: route.name + "index",
                    menuName: route.meta.title,
                    meta: {} ,
                    component: route.component
                }]
            }
            route.component = Layout;
        } else {
            if (route.component && componentMap.has(route.component)) {
                route.component = componentMap.get(route.component);
            } else {
                delete route.component;
            }
        }

        if (route.children.length > 0) {


            if (route.children.filter(value => value.visible == 0).length > 0) {

                let firstChild = route.children.filter(value => value.visible == 0)[0];
                if (firstChild) {
                    let redirect = route.path + firstChild.url;
                    route.redirect = redirect;
                }
            }


            convertRouter(route.children,route);
        }
    }
};



/**
 * 根据path路径获取matched
 * @param routes 菜单routes
 * @param name 路由名
 * @returns {*} matched
 */
/**
 * 根据path路径获取matched
 * @param routes 菜单routes
 * @param path 路径
 * @returns {*} matched
 */
export const handleMatched = (
    routes: VabRouteRecord[],
    path: string
): VabRouteRecord[] => {
    return routes
        .filter((route) => route.childrenPathList && route.childrenPathList.indexOf(path) + 1)
        .flatMap((route) =>
            route.children ? [route, ...handleMatched(route.children, path)] : [route]
        );
};

/**
 * 生成单个多标签元素，可用于同步/异步添加多标签
 * @param tag route页信息
 */
export const handleTabs = (tag: VabRoute) => {
    let parentIcon = null;
    if (tag.matched)
        for (let i = tag.matched.length - 2; i >= 0; i--)
            if (!parentIcon && tag.matched[i].meta.icon)
                parentIcon = tag.matched[i].meta.icon;
    if (!parentIcon) parentIcon = "menu-line";
    console.log("before handle active path",tag)
    const path = handleActivePath(tag, true);
    console.log("handle tabs path: ",path,tag)
    if (tag.name && tag.meta && tag.meta.tabHidden !== true) {
        return {
            path,
            query: tag.query,
            params: tag.params,
            name: tag.name,
            parentIcon,
            meta: {...tag.meta},
        };
    }
};

/**
 * 根据当前route获取激活菜单
 * @param route 当前路由
 * @param isTab 是否是标签
 * @returns {string|*}
 */
export const handleActivePath = (route: VabRoute, isTab = false) => {
    const {meta, path, matched, query}: any = route;
    const rawPath = matched ? matched.at(-1).path : path;
    const fullPath =
        query && Object.keys(query).length > 0
            ? `${path}?${stringify(query)}`
            : path;
    if (isTab) return meta.dynamicNewTab ? fullPath : rawPath;
    if (meta.activeMenu) return meta.activeMenu;
    return fullPath;
};

/**
 * 获取当前跳转登录页的Route
 * @param currentPath 当前页面地址
 */
export const toLoginRoute = (currentPath: string) => {
    if (recordRoute && currentPath !== "/")
        return {
            path: "/login",
            query: {redirect: currentPath},
            replace: true,
        };
    else return {path: "/login", replace: true};
};

/**
 * 获取路由中所有的Name
 * @param routes 路由数组
 * @returns {*} Name数组
 */
export const getNames = (routes: VabRouteRecord[]): string[] => {
    return routes.flatMap((route: VabRouteRecord) => {
        const names = [];
        if (route.name) names.push(route.name);
        if (route.children) names.push(...getNames(route.children));
        return names;
    });
};
